package com.kandinfo.isbnmanage.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.kandinfo.base.common.constant.ResultCode;
import com.kandinfo.base.common.converter.ConverterService;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.util.AppConfigUtil;
import com.kandinfo.base.common.util.PicUploader;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.isbnmanage.domian.HomeworkTemporary;
import com.kandinfo.isbnmanage.domian.IsbnInformation;
import com.kandinfo.isbnmanage.domian.IsbnManage;
import com.kandinfo.isbnmanage.domian.IsbnOrder;
import com.kandinfo.isbnmanage.dto.IsbnInformationDto;
import com.kandinfo.isbnmanage.dto.IsbnOrderDto;
import com.kandinfo.isbnmanage.repository.HomeworkTemporaryRepository;
import com.kandinfo.isbnmanage.repository.IsbnBusinessRepository;
import com.kandinfo.isbnmanage.repository.IsbnManageRepository;
import com.kandinfo.isbnmanage.repository.IsbnOrderRepository;
import com.kandinfo.isbnmanage.repository.IsbnPageRepository;
import com.kandinfo.isbnmanage.service.IsbnInformationService;
import com.kandinfo.isbnmanage.service.IsbnManageService;
import com.kandinfo.isbnmanage.service.IsbnSaveAndUpdateService;
import com.kandinfo.isbnmanage.util.AliyunOSSUtil;



@Service
public class IsbnSaveAndUpdateServiceImpl implements IsbnSaveAndUpdateService {
	
	@Autowired
	private IsbnInformationService isbnInformationService;
	
	@Autowired
	private IsbnManageRepository isbnManageRepository;
	
	@Autowired
	private IsbnManageService isbnManageService;
	
	@Autowired
	private IsbnOrderRepository isbnOrderRepository;
	
	@Autowired
	private HomeworkTemporaryRepository homeworkTemporaryRepository;
	
	@Autowired
    private SecurityContext securityContext;
	
	@Autowired
	private IsbnBusinessRepository isbnBusinessRepository;
	
	@Autowired
	private IsbnPageRepository isbnPageRepository;
	
	@Autowired
	private AliyunOSSUtil aliyunOSSUtil;
	
	private final static String FILE_AT = "@";
	private final static String FILE_SPRATE = "/";
	private final static String FILE_END = "?";
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultDto informationSaveAndUpdate(IsbnInformationDto isbnInformationResDto) throws Exception {
		if (isbnInformationResDto == null) {
			throw new Exception("isbn信息为空！");
		}
		if (StringUtils.isNotEmpty(isbnInformationResDto.getName())) {
			Integer repeatNameCount = isbnBusinessRepository.getRepeatInfoNameCount(isbnInformationResDto.getName(),isbnInformationResDto.getId());
			if (repeatNameCount > 0 ) {
				throw new Exception("书名重复！");
			}
		}
		
		Integer repeatCount = isbnBusinessRepository.getRepeatInfoCount(isbnInformationResDto);
		if (repeatCount > 0 ) {
			throw new Exception("IsbnInformation信息重复！");
		}
		Long curUserId = SecurityContext.getInstance().getCurrentUserId();
		Date date = new Date();
		IsbnInformation isbnInformation = ConverterService.convert(isbnInformationResDto, IsbnInformation.class);
		if (isbnInformation.getId() != null) {
			//更新
			isbnInformation.setUpdateBy(curUserId);
			isbnInformation.setUpdateTs(date);
		}else {
			//保存
			isbnInformation.setCreateBy(curUserId);
			isbnInformation.setCreateTs(date);
		}
		
		Integer hasAnswer = isbnInformation.getHasAnswer();
		if (hasAnswer != null) {
			homeworkTemporaryRepository.updateHasAnswerByIsbnInfoId(isbnInformation.getId(),hasAnswer);
		}
		
		isbnInformationService.save(isbnInformation);
		return ResultDtoFactory.toAck("isbn信息保存成功", isbnInformation);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultDto orderSaveAndUpdate(IsbnOrderDto isbnOrderReqDto) throws Exception {
		if (isbnOrderReqDto == null) {
			throw new Exception("订单信息为空！");
		} else if (isbnOrderReqDto.getStatus() == null) {
			throw new Exception("采购状态为必选项！");
		}
		Long curUserId = SecurityContext.getInstance().getCurrentUserId();
		Date date = new Date();
		IsbnOrder isbnOrder = ConverterService.convert(isbnOrderReqDto, IsbnOrder.class);
		if (isbnOrder.getId() != null) {
			//更新
			isbnOrder.setUpdateBy(curUserId);
			isbnOrder.setUpdateTs(date);
			
		}else {
			//保存
			isbnOrder.setCreateBy(curUserId);
			isbnOrder.setCreateTs(date);
			
			IsbnOrder isbnOrderLocal = isbnOrderRepository.get(isbnOrderReqDto.getBarcode(),isbnOrderReqDto.getIsbnInformationId());
			if (isbnOrderLocal !=  null) {
				isbnOrder.setId(isbnOrderLocal.getId());
			}
		}
		isbnOrderRepository.save(isbnOrder);
		
		//统计已下单信息
		String barcode = isbnOrder.getBarcode();
		if (StringUtils.isEmpty(barcode)) {
			throw new Exception("条形码信息为空！");
		}
		IsbnManage isbnManage = isbnManageRepository.getByBarcode(barcode);
		if (isbnManage == null) {
			throw new Exception("isbnManage信息不存在！");
		}
		//统计isbn order数量 未买到除外
		Integer countWithOrder = isbnOrderRepository.countWithOrder(barcode);
		Integer countWithoutOrder = isbnOrderRepository.countWithoutOrder(barcode);
		
		if (3 == isbnOrderReqDto.getStatus()) {
			isbnManage.setReceiptCount(isbnOrderRepository.countWithOrderByStatus(barcode, 3) + isbnOrderRepository.countWithoutOrderByStatus(barcode, 3));
		}
		
		isbnManage.setOrderCount(countWithOrder+countWithoutOrder);
		isbnManage.setUpdateBy(curUserId);
		isbnManage.setCreateTs(date);
		isbnManageService.save(isbnManage);
		
		return ResultDtoFactory.toAck("订单信息保存成功", isbnOrder);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultDto uploadFile(HttpServletRequest request, HttpServletResponse response, Long homeworkId , String isCover) {
		response.setContentType("text/html;charset=UTF-8");
        MultipartHttpServletRequest mhr = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> filemaps = mhr.getFileMap();
        Set<String> keys = filemaps.keySet();
        IsbnInformation isbnInformation = isbnInformationService.findOne(homeworkId);
        if (isbnInformation == null) {
			return ResultDtoFactory.toNack("IsbnInformation信息不存在!");
		}
        String barcode = isbnInformation.getBarcode();
        if (StringUtils.isEmpty(isbnInformation.getBarcode())) {
        	return ResultDtoFactory.toNack("IsbnInformation条形码信息不存在!");
		}
        List<HomeworkTemporary> homeworkTemporaryList = new ArrayList<HomeworkTemporary>();
        int maxShowCount = 0;
        String uploadSuccessNames = "";
        for (String string : keys) {
        	MultipartFile file = filemaps.get(string);
            String fileName = file.getOriginalFilename();
            Long fileSize = file.getSize();
            Integer pageNum = null;
            try {
            	pageNum = Integer.parseInt(fileName.substring(0, fileName.indexOf(".")));
			} catch (Exception e) {
				return ResultDtoFactory.toNack("图片名只能是数字，不能为["+fileName+"]");
			}
            if ("0".equals(isCover)  &&  pageNum != 0) {
            	return ResultDtoFactory.toNack("封面命名只能是一个或多个 0 ，不能为["+fileName+"]");
			}
            if ("1".equals(isCover) && pageNum == 0) {
            	return ResultDtoFactory.toNack("内容图片文件名只能是大于等于 1的数字，不能为["+fileName+"]");
			}
            String subPath = AppConfigUtil.getConfig("oss_upload") + FILE_SPRATE + barcode + FILE_SPRATE + homeworkId;
            String pageImageUrl = "";
			try {
	            //上传图片到图片服务器
				String key = aliyunOSSUtil.uploadFile(file.getInputStream(), fileName, subPath);
				pageImageUrl = aliyunOSSUtil.getUrl(subPath+FILE_SPRATE+key);
//				ResultDto result = PicUploader.doUpload((FileInputStream) file.getInputStream(), fileName, subPath);
//				if (result.getCode() == ResultCode.NACK) {
//	            	return result;
//				}
			} catch (IOException e) {
				return ResultDtoFactory.toNack("读取文件["+fileName+"]异常：" + e.getMessage());
			}
            
            //3.如果文件上传成功 需要把对应信息保存到数据库中
            HomeworkTemporary homeworkTemporary = homeworkTemporaryRepository.get(barcode, homeworkId, fileName);
            Long userId = securityContext.getCurrentUserId();
            if(homeworkTemporary == null) {
            	homeworkTemporary = new HomeworkTemporary();
                homeworkTemporary.setCreateBy(userId);
                homeworkTemporary.setCreateTs(new Date());
                homeworkTemporary.setHomeworkId(homeworkId);
                homeworkTemporary.setIsCover(isCover);
                homeworkTemporary.setPageImageUrl(pageImageUrl);
                homeworkTemporary.setStatus("0");
                homeworkTemporary.setBarcode(barcode);
                homeworkTemporary.setFileName(fileName);
                homeworkTemporary.setFileSize(fileSize);
            } else {
                homeworkTemporary.setStatus("0");
                homeworkTemporary.setPageImageUrl(pageImageUrl);
                homeworkTemporary.setUpdateBy(userId);
                homeworkTemporary.setUpdateTs(new Date());
                homeworkTemporary.setIsCover(isCover);
                homeworkTemporary.setFileName(fileName);
                homeworkTemporary.setFileSize(fileSize);
            }
            if (isbnInformation.getHasAnswer() != null) {
            	homeworkTemporary.setHasAnswer(isbnInformation.getHasAnswer().toString());
			}
            if ("0".equals(isCover)) {
				isbnInformation.setCoverImageUrl(pageImageUrl);
				isbnInformationService.save(isbnInformation);
			}
            homeworkTemporaryRepository.save(homeworkTemporary);
            homeworkTemporaryList.add(homeworkTemporary);
            if(++maxShowCount < 10) {
            	uploadSuccessNames += uploadSuccessNames.length() == 0 ? fileName : "," + fileName;
            }
        }
		return ResultDtoFactory.toAck("图片["+uploadSuccessNames+(maxShowCount>=9?"...等":"")+"]上传成功!", homeworkTemporaryList);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultDto deletePage(Long homeworkTemporaryId) {
		if (homeworkTemporaryId == null) {
			return ResultDtoFactory.toNack("homeworkTemporaryId不存在！");
		}
		HomeworkTemporary homeworkTemporary = homeworkTemporaryRepository.findOne(homeworkTemporaryId);
		if (homeworkTemporary == null) {
			return ResultDtoFactory.toNack("HomeworkTemporary信息不存在！");
		}
		String fileName = getFileName(homeworkTemporary);
		if (StringUtils.isEmpty(fileName)) {
			return ResultDtoFactory.toNack("无法获取文件名！");
		}
		Long isbnInformationId = homeworkTemporary.getHomeworkId();
		if ("0".equals(homeworkTemporary.getIsCover())) {
			IsbnInformation isbnInformation = isbnInformationService.findOne(isbnInformationId);
	        if (isbnInformation == null) {
				return ResultDtoFactory.toNack("IsbnInformation信息不存在!");
			}
	        isbnInformation.setCoverImageUrl(null);
	        isbnInformationService.save(isbnInformation);
		}
		homeworkTemporaryRepository.delete(homeworkTemporary);
		homeworkTemporaryRepository.deletePage(isbnInformationId, fileName, homeworkTemporaryId);
		isbnPageRepository.deletePage(isbnInformationId, fileName);
		aliyunOSSUtil.deleteFile(aliyunOSSUtil.getKeyFromUrl(homeworkTemporary.getPageImageUrl()));
		return ResultDtoFactory.toAck("删除成功！");
	}

	private String getFileName(HomeworkTemporary homeworkTemporary){
		String fileName = homeworkTemporary.getFileName();
		if (StringUtils.isEmpty(fileName)) {
			String imgUrl = homeworkTemporary.getPageImageUrl();
			int beginIndex = imgUrl.lastIndexOf(FILE_AT) > -1 ? imgUrl.lastIndexOf(FILE_AT) : imgUrl.lastIndexOf(FILE_SPRATE);
			int endIndex = imgUrl.lastIndexOf(FILE_END) > -1 ? imgUrl.lastIndexOf(FILE_END) : imgUrl.length();
			fileName =  imgUrl.substring(beginIndex+1, endIndex).trim();
		}
		return fileName;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultDto deleteCover(Long isbnInformationId) {
        HomeworkTemporary homeworkTemporary = homeworkTemporaryRepository.findCoverByHomeworkId(isbnInformationId);
        return deletePage(homeworkTemporary.getId());
	}
	
}
